<template>
  <div v-if="visible" class="game-settlement-overlay" @click="handleOverlayClick">
    <div class="game-settlement-dialog" @click.stop>
      <div class="settlement-header">
        <h2 class="settlement-title">🎉 游戏结算</h2>
        <button class="close-btn" @click="$emit('close')">×</button>
      </div>
      
      <div class="settlement-content">
        <!-- 游戏结果 -->
        <div class="result-section">
          <div class="result-icon" :class="resultClass">
            {{ resultIcon }}
          </div>
          <h3 class="result-text">{{ resultText }}</h3>
          <p class="result-desc">{{ resultDesc }}</p>
        </div>
        
        <!-- 玩家排名 -->
        <div class="ranking-section" v-if="leaderboard && leaderboard.length > 0">
          <h4 class="section-title">🏆 最终排名</h4>
          <div class="ranking-list">
            <div 
              v-for="(player, index) in sortedLeaderboard" 
              :key="player.playerId"
              class="ranking-item"
              :class="{ 'current-player': player.playerId === currentPlayerId }"
            >
              <div class="rank-number" :class="`rank-${index + 1}`">
                {{ index + 1 }}
              </div>
              <div class="player-info">
                <div class="player-name">{{ player.username || player.playerName || '未知玩家' }}</div>
                <div class="player-stats">
                  <span class="area-count">面积: {{ player.areaCount || 0 }}</span>
                  <span class="score">得分: {{ player.score || 0 }}</span>
                </div>
              </div>
              <div class="exp-gain" v-if="player.expGain">
                <span class="exp-icon">⭐</span>
                <span class="exp-text">+{{ player.expGain }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 游戏统计 -->
        <div class="stats-section" v-if="gameStats">
          <h4 class="section-title">📊 游戏统计</h4>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-label">游戏时长</div>
              <div class="stat-value">{{ formatDuration(gameStats.duration) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">总涂色面积</div>
              <div class="stat-value">{{ gameStats.totalArea }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">参与玩家</div>
              <div class="stat-value">{{ gameStats.playerCount }}</div>
            </div>
          </div>
        </div>
        
        <!-- 经验值获得 -->
        <div class="exp-section" v-if="currentPlayerExp">
          <h4 class="section-title">⭐ 经验值获得</h4>
          <div class="exp-display">
            <div class="exp-before">
              <span class="exp-label">当前等级:</span>
              <span class="exp-value">{{ currentPlayerExp.currentLevel }}</span>
            </div>
            <div class="exp-progress">
              <div class="exp-bar">
                <div 
                  class="exp-fill" 
                  :style="{ width: `${currentPlayerExp.progressPercentage}%` }"
                ></div>
              </div>
              <span class="exp-text">
                {{ currentPlayerExp.currentExp }}/{{ currentPlayerExp.expToNextLevel }}
              </span>
            </div>
            <div class="exp-gain-display">
              <span class="exp-gain-label">本次获得:</span>
              <span class="exp-gain-value">+{{ currentPlayerExp.expGain }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="settlement-actions">
        <button class="action-btn primary" @click="playAgain">
          🎮 再来一局
        </button>
        <button class="action-btn secondary" @click="backToLobby">
          🏠 返回大厅
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

export default {
  name: 'GameSettlementDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    gameResult: {
      type: Object,
      default: () => ({})
    },
    leaderboard: {
      type: Array,
      default: () => []
    },
    gameStats: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['close', 'play-again'],
  setup(props, { emit }) {
    const router = useRouter()
    const userStore = useUserStore()
    
    const currentPlayerId = computed(() => userStore.user?.id)
    
    // 计算游戏结果
    const resultClass = computed(() => {
      const currentPlayer = props.leaderboard?.find(p => p.playerId === currentPlayerId.value)
      if (!currentPlayer) return 'draw'
      
      if (currentPlayer.rank === 1) return 'victory'
      if (currentPlayer.rank === props.leaderboard.length) return 'defeat'
      return 'draw'
    })
    
    const resultIcon = computed(() => {
      switch (resultClass.value) {
        case 'victory': return '🏆'
        case 'defeat': return '😔'
        default: return '🤝'
      }
    })
    
    const resultText = computed(() => {
      switch (resultClass.value) {
        case 'victory': return '恭喜获胜！'
        case 'defeat': return '再接再厉！'
        default: return '平局结束！'
      }
    })
    
    const resultDesc = computed(() => {
      switch (resultClass.value) {
        case 'victory': return '你成功占领了最多的地盘！'
        case 'defeat': return '下次一定能做得更好！'
        default: return '大家势均力敌，不分胜负！'
      }
    })
    
    // 排序排行榜
    const sortedLeaderboard = computed(() => {
      return [...props.leaderboard].sort((a, b) => (a.rank || 0) - (b.rank || 0))
    })
    
    // 当前玩家经验值信息
    const currentPlayerExp = computed(() => {
      const currentPlayer = props.leaderboard?.find(p => p.playerId === currentPlayerId.value)
      if (!currentPlayer) return null
      
      // 这里可以根据实际的经验值系统计算
      // 暂时使用模拟数据
      return {
        currentLevel: 5,
        currentExp: 750,
        expToNextLevel: 1000,
        progressPercentage: 75,
        expGain: currentPlayer.expGain || 50
      }
    })
    
    // 格式化时长
    const formatDuration = (seconds) => {
      if (!seconds) return '0秒'
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      if (minutes > 0) {
        return `${minutes}分${remainingSeconds}秒`
      }
      return `${remainingSeconds}秒`
    }
    
    // 再来一局
    const playAgain = () => {
      emit('play-again')
    }
    
    // 返回大厅
    const backToLobby = () => {
      router.push('/rooms')
    }
    
    // 点击遮罩关闭
    const handleOverlayClick = () => {
      emit('close')
    }
    
    return {
      currentPlayerId,
      resultClass,
      resultIcon,
      resultText,
      resultDesc,
      sortedLeaderboard,
      currentPlayerExp,
      formatDuration,
      playAgain,
      backToLobby,
      handleOverlayClick
    }
  }
}
</script>

<style scoped>
.game-settlement-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(4px);
}

.game-settlement-dialog {
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.settlement-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 24px 16px;
  border-bottom: 1px solid #e5e7eb;
}

.settlement-title {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #111827;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.settlement-content {
  padding: 24px;
}

.result-section {
  text-align: center;
  margin-bottom: 32px;
}

.result-icon {
  font-size: 64px;
  margin-bottom: 16px;
  animation: bounce 0.6s ease-in-out;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-20px);
  }
  60% {
    transform: translateY(-10px);
  }
}

.result-text {
  margin: 0 0 8px;
  font-size: 28px;
  font-weight: 700;
  color: #111827;
}

.result-desc {
  margin: 0;
  font-size: 16px;
  color: #6b7280;
}

.ranking-section {
  margin-bottom: 32px;
}

.section-title {
  margin: 0 0 16px;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f9fafb;
  border-radius: 12px;
  border: 2px solid transparent;
  transition: all 0.2s;
}

.ranking-item.current-player {
  border-color: #3b82f6;
  background: #eff6ff;
}

.rank-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 18px;
  margin-right: 16px;
}

.rank-1 {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  color: white;
}

.rank-2 {
  background: linear-gradient(135deg, #9ca3af, #6b7280);
  color: white;
}

.rank-3 {
  background: linear-gradient(135deg, #d97706, #b45309);
  color: white;
}

.rank-4, .rank-5 {
  background: #e5e7eb;
  color: #6b7280;
}

.player-info {
  flex: 1;
}

.player-name {
  font-weight: 600;
  color: #111827;
  margin-bottom: 4px;
}

.player-stats {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #6b7280;
}

.exp-gain {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 600;
  color: #059669;
}

.exp-icon {
  font-size: 16px;
}

.stats-section {
  margin-bottom: 32px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f9fafb;
  border-radius: 12px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #111827;
}

.exp-section {
  margin-bottom: 32px;
}

.exp-display {
  background: #f9fafb;
  padding: 20px;
  border-radius: 12px;
}

.exp-before {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.exp-label {
  font-size: 14px;
  color: #6b7280;
}

.exp-value {
  font-size: 18px;
  font-weight: 600;
  color: #111827;
}

.exp-progress {
  margin-bottom: 16px;
}

.exp-bar {
  width: 100%;
  height: 8px;
  background: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.exp-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #1d4ed8);
  transition: width 0.3s ease;
}

.exp-text {
  font-size: 14px;
  color: #6b7280;
}

.exp-gain-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exp-gain-label {
  font-size: 14px;
  color: #6b7280;
}

.exp-gain-value {
  font-size: 20px;
  font-weight: 700;
  color: #059669;
}

.settlement-actions {
  display: flex;
  gap: 16px;
  padding: 24px;
  border-top: 1px solid #e5e7eb;
}

.action-btn {
  flex: 1;
  padding: 14px 24px;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.primary {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  color: white;
}

.action-btn.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
}

.action-btn.secondary {
  background: #f3f4f6;
  color: #374151;
  border: 2px solid #e5e7eb;
}

.action-btn.secondary:hover {
  background: #e5e7eb;
  border-color: #d1d5db;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .game-settlement-dialog {
    width: 95%;
    margin: 20px;
  }
  
  .settlement-header {
    padding: 20px 20px 16px;
  }
  
  .settlement-content {
    padding: 20px;
  }
  
  .settlement-actions {
    padding: 20px;
    flex-direction: column;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
